#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    relations = new RelationFrame();
    newDialog = new NewDialog();
    ui->horizontalLayout->addWidget(relations);
    relations->hide();
    ui->statusBar->showMessage(tr("No database loaded."));
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::changeEvent(QEvent *e)
{
    QMainWindow::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void MainWindow::on_actionNew_activated()
{
    QString filename = QFileDialog::getSaveFileName(this, tr("Save Database As"), "~",tr("PepBase Files (*.pepbase)"));
    if (!filename.endsWith(".pepbase"))
    {
        filename += ".pepbase";
    }
    metadataFile.setFileName(filename);
    if (!metadataFile.open(QIODevice::ReadWrite))
    {
        ui->statusBar->showMessage(tr("Error: could not create ") + filename);
        return;
    }
    ui->statusBar->showMessage(filename + tr(" created."));
    ui->listWidget->setEnabled(true);
    ui->listWidget->setCurrentRow(0);
    ui->label_info->setText("Database: " + filename);
}

void MainWindow::on_actionOpen_activated()
{
    QString filename = QFileDialog::getOpenFileName(this, tr("Open Existing Database"), "",tr("PepBase Files (*.pepbase)"));
    if (filename == "")
    {
        return;
    }
    metadataFile.close();
    metadataFile.setFileName(filename);
    if (!metadataFile.open(QIODevice::ReadWrite))
    {
        ui->statusBar->showMessage(tr("Error: could not open ") + filename);
        return;
    }
    ui->statusBar->showMessage(filename + tr(" opened."));
    ui->listWidget->setEnabled(true);
    ui->listWidget->setCurrentRow(0);
    ui->label_info->setText("Database: " + filename);
}

void MainWindow::on_listWidget_currentRowChanged(int row)
{
    switch(row)
    {
    case 1:
        ui->frame->hide();
        relations->show();
        break;
    default:
        relations->hide();
        ui->frame->show();
    }
}
